package com.spring.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import com.spring.aicloud.entity.Answer;
import com.spring.aicloud.entity.enums.AiModelEnum;
import com.spring.aicloud.entity.enums.AiTypeEnum;
import com.spring.aicloud.service.IAnswerService;
import com.spring.aicloud.util.AppVariable;
import com.spring.aicloud.util.ResponseEntity;
import com.spring.aicloud.util.SecurityUtil;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiImageClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 调用云端 OpenAI 大模型
 */
@RestController
@RequestMapping("/openai")
public class OpenAIController {

    @Resource
    private OpenAiChatClient chatModel;
    @Resource
    private OpenAiImageClient imageModel;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 调用 Open AI 聊天接口
     *
     * @param question
     * @return
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return ResponseEntity.fail("请先输入内容！");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口！");
            }
            // 调用 Open AI 接口
            result = chatModel.call(question);
            // 将结果保存到数据库中
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.OPENAI.getValue());
            answer.setType(AiTypeEnum.CHAT.getValue());
            answer.setUid(uid);
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            // 释放锁
            rLock.unlock();
        }
        if (isSave) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("数据保存失败，请重试！");
    }

    /**
     * 实现绘图功能
     *
     * @param question
     * @return
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return ResponseEntity.fail("请先输入内容！");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(),
                AiTypeEnum.DRAW.getValue());
        String imgUrl = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 掉用 Open AI 接口
            ImageResponse result = imageModel.call(new ImagePrompt(question));
            imgUrl = result.getResult().getOutput().getUrl();
            // 将结果保存到数据库中
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(imgUrl);
            answer.setModel(AiModelEnum.OPENAI.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            isSave = answerService.save(answer);
        } finally {
            rLock.unlock();
        }
        if (isSave) {
            return ResponseEntity.succ(imgUrl);
        }
        return ResponseEntity.fail("数据保存失败，请重试！");
    }

    /**
     * 获取 OpenAI 聊天历史信息
     *
     * @return
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.OPENAI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) { // 缓存不存在
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            // 存储到缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }

    /**
     * 获取绘图历史信息
     *
     * @return
     */
    @RequestMapping("/getdrawlist")
    public ResponseEntity getDrawList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        queryWrapper.eq("type", AiTypeEnum.DRAW.getValue());
        queryWrapper.eq("model", AiModelEnum.OPENAI.getValue());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.succ(answerService.list(queryWrapper));
    }

}
